package top.lingkang.finalvalidated.handle;

import top.lingkang.finalvalidated.constraints.Length;
import top.lingkang.finalvalidated.core.FinalValidatorFactory;
import top.lingkang.finalvalidated.error.CheckException;
import top.lingkang.finalvalidated.error.ValidatedException;
import top.lingkang.finalvalidated.utils.FinalValidatorUtils;

/**
 * @author lingkang
 * Created by 2024/1/26
 */
public class LengthHandle extends ValidHandle {
    private final String errorStr;
    private final Length length;

    public LengthHandle(ValidVal validVal, Length length) {
        super(validVal, length);
        this.length = length;
        if (length.min() > length.max())
            throw new CheckException("@Length 所配置的min值不能大于max值，属性名称：" + validVal.getName());
        if (length.min() < 0)
            throw new CheckException("@Length 所配置的min值不能小于 0 ，属性名称：" + validVal.getName());

        if (FinalValidatorUtils.isNotEmpty(length.message())) {
            errorStr = length.message();
        } else if (FinalValidatorUtils.isNotEmpty(validVal.getTag())) {
            errorStr = FinalValidatorFactory.message.getProperty("Length")
                    .replace("{attrName}", validVal.getTag())
                    .replace("{min}", Long.toString(length.min()))
                    .replace("{max}", Long.toString(length.max()));
        } else {
            errorStr = FinalValidatorFactory.message.getProperty("Length")
                    .replace("{attrName}", validVal.getName())
                    .replace("{min}", Long.toString(length.min()))
                    .replace("{max}", Long.toString(length.max()));
        }
    }

    @Override
    public void valid(Object target) {
        if (length.min() == 0)
            return;
        Object o = validVal.getValGet().get(target);
        if (o == null || o.toString().length() < length.min() || o.toString().length() > length.max()) {
            throw new ValidatedException(errorStr, validVal);
        }
    }

    @Override
    public Class<?>[] getGroups() {
        return length.groups();
    }
}
